package nuc.soft.xsf.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;
import nuc.soft.xsf.model.Paper;
import nuc.soft.xsf.model.Report;
import nuc.soft.xsf.model.Role;
import nuc.soft.xsf.model.Title;
import nuc.soft.xsf.model.TitlePaper;
import nuc.soft.xsf.model.Titletype;
import nuc.soft.xsf.model.User;
import nuc.soft.xsf.model.UserPaper;
import nuc.soft.xsf.service.IPaperService;
import nuc.soft.xsf.service.IReportService;
import nuc.soft.xsf.service.IRoleService;
import nuc.soft.xsf.service.ITitlePaperService;
import nuc.soft.xsf.service.ITitleService;
import nuc.soft.xsf.service.ITitletypeService;
import nuc.soft.xsf.service.IUserPaperService;
import nuc.soft.xsf.service.IUserService;
import nuc.soft.xsf.tools.Tools;

import org.apache.commons.lang.StringUtils;
import org.junit.runners.Parameterized.Parameters;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/UserPaperController", produces = "text/html;charset=UTF-8")
public class UserPaperController {
	@Resource
	private IUserPaperService userPaperService;

	@Resource
	private IReportService reportService;

	@Resource
	private ITitleService titleService;

	@Resource
	private ITitlePaperService titlePaperService;

	@Resource
	private ITitletypeService titletypeService;

	@Resource
	private IPaperService paperService;

	@Resource
	private IUserService userService;

	@Resource
	private IRoleService roleService;

	@RequestMapping(value = "/add.action", produces = "text/html;charset=UTF-8")
	public String getUserAnswer(Title title, int judgepara,
			HttpServletRequest request) {
		// 获取用户Id
		float sum = 0;
		User u = new User();
		int userId = (int) request.getSession().getAttribute("UserId");
		u.setUserId(userId);
		UserPaper userPaper = new UserPaper();
		userPaper.setPaperId(title.getTitleId());
		userPaper.setUserId(u.getUserId());
		// 获取用户的答案和对应的题号
		// 存储用户答案
		// 空
		if (title.getExtend1() != null) {
			userPaper.setExtend1(title.getExtend1());
		}
		// 题目的题号
		userPaper.setExtend2(title.getNote());
		String[] str = title.getNote().split(",");
		String[] userAnswer =new String[str.length];
		String[] userAnswer02=userPaper.getExtend1().split(",");
		for(int i=0;i<userAnswer.length;i++){
			if(i<userAnswer02.length){
			userAnswer[i]=userAnswer02[i];
			}
			else{
			userAnswer[i]="";
			}
		}
		
		System.out.println(userAnswer.length);
		// 得分
		Float[] newString = new Float[str.length];
		float userScore = 0;
		float sumScore = 0;
		for (int i = 0; i < userAnswer.length; i++) {
			newString[i] = (float) 0.0;
			Title title01 = new Title();
			if (str.length > 0) {
				if (str[i] != null && !str[i].equals("")) {
					title01 = titleService.findById(Integer.parseInt(str[i]));
					if (title01 != null) {
						if (userAnswer.length > 0 && userAnswer.length > 0
								&& userAnswer[i] != null) {
							if (userAnswer[i].indexOf(" ") == -1) {
								if (userAnswer[i].equals("A")) {
									if (title01.getAnsweraScore() != null) {
										userScore = title01.getAnsweraScore();
									} else {
										userScore = 0;
									}
									newString[i] = userScore;
									sumScore += userScore;
								}
								if (userAnswer[i].equals("B")) {
									if (title01.getAnswerbScore() != null) {
										userScore = title01.getAnswerbScore();
									} else {
										userScore = 0;
									}
									newString[i] = userScore;
									sumScore += userScore;

								}
								if (userAnswer[i].equals("C")) {
									if (title01.getAnswercScore() != null) {
										userScore = title01.getAnswercScore();
									} else {
										userScore = 0;
									}
									newString[i] = userScore;
									sumScore += userScore;
								}
								if (userAnswer[i].equals("D")) {
									if (title01.getAnswerdScore() != null) {
										userScore = title01.getAnswerdScore();
									} else {
										userScore = 0;
									}
									newString[i] = userScore;
									sumScore += userScore;
								}

							} else {
								String[] strUserAnswer = userAnswer[i]
										.split(" ");
								for (int k = 0; k < strUserAnswer.length; k++) {
									if (strUserAnswer[k].equals("A")) {
										newString[i] += title01.getAnsweraScore();
										sumScore += title01.getAnsweraScore();
									}
									if (strUserAnswer[k].equals("B")) {
										newString[i]+= title01.getAnswerbScore();
										sumScore += title01.getAnsweraScore();
									}
									if (strUserAnswer[k].equals("C")) {
										newString[i] += title01.getAnswerbScore();
										sumScore += title01.getAnsweraScore();
									}
									if (strUserAnswer[k].equals("D")) {
										newString[i]+= title01
												.getAnswerbScore();
										sumScore += title01.getAnsweraScore();
									}
									System.out.println("sumScore" + sumScore);
								}
							}
						} else {
							newString[i] = (float) 0.0;
							sumScore += newString[i];
						}
					}

				}
			}
		}
		// 将字符串数组转换为字符串
		String str1 = StringUtils.join(newString, ",");

		// 将用户每道题的分数保存起来
		userPaper.setTitleUserscore(str1);
		// 试卷的总分
		userPaper.setSumScore(sumScore);
		userPaper.setDeletestate(0);
		// 返回用户试卷的ID
		int id1 = userPaperService.insert(userPaper);
		System.out.println(id1);
		JSONObject json = new JSONObject();
		json.put("data", userPaper);
		Paper paper=paperService.findById(userPaper.getPaperId());
		// 同时生成报表
		Report report = new Report();
		report.setUserId(u.getUserId());
		report.setReportName(paper.getPaperName()+"测评报告");
		report.setDeletestate(0);
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式 
		String data=df.format(new Date());
		// 返回报告的ID
		report.setExtend2(data);
		int id = reportService.insert(report);
		UserPaper userpaper01 = userPaperService.findById(id1);
		userpaper01.setReportId(id);
		// 更新 建立了报表和用户试卷表的关联
		userPaperService.update(userpaper01);
		return "redirect:/pages/index.jsp";
		

	}

	@RequestMapping(value = "/findByCondition.action", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String findByCondition(UserPaper userPaper,
			HttpServletRequest request) {
		Map map = Tools.transBean2Map(userPaper);
		JSONObject json = new JSONObject();
		List<UserPaper> userPaperList = userPaperService.findByCondition(map);
		json.put("list", userPaperList);
		return json.getString("list");

	}

	@RequestMapping(value = "/findByconditionUserId.action", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String findByReport(int userId, HttpServletRequest request) {
		UserPaper userPaper = new UserPaper();
		userPaper.setUserId(userId);
		System.out.println(userId);
		Map map = Tools.transBean2Map(userPaper);
		List<UserPaper> userPaperList = userPaperService.findByCondition(map);
		List list = new ArrayList();
		for (int i = 0; i < userPaperList.size(); i++) {
			Report report = new Report();
			report.setReportId(userPaperList.get(i).getReportId());
			report = reportService.findById(report.getReportId());
			list.add(report);
		}
		System.out.println(list.toString());
		JSONObject json = new JSONObject();
		json.put("list", list);
		return json.getString("list");
	}

	// 通过报告号查询
	@RequestMapping(value = "/findBygroup.action", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String findBygroup(UserPaper userPaper, HttpServletRequest request) {
		int userId = (int) request.getSession().getAttribute("UserId");
		String state = userService.findById(userId).getUserState();
		Role role = roleService.findById(Integer.parseInt(state));
		Map map = Tools.transBean2Map(userPaper);
		List<UserPaper> userPaperList = userPaperService.findByCondition(map);
		// 通过reportID找到paperId
		int paperId = userPaperList.get(0).getPaperId();
		System.out.println("试卷ID" + paperId);
		Paper paper = paperService.findById(paperId);
		String str = userPaperList.get(0).getTitleUserscore();
		
	
		String[] strListUser = str.split(",");
		// 查询到所有做完该份试卷的记录
		UserPaper userPaper01 = new UserPaper();
		userPaper01.setPaperId(paperId);

		Map map02 = Tools.transBean2Map(userPaper01);
		List<UserPaper> list = userPaperService.findByCondition(map02);
	
		float avgPaperScore = 0;
		List<String[]> listUserScore = new ArrayList<String[]>();
		for (int x = 0; x < list.size(); x++) {
			String str02 = list.get(x).getTitleUserscore();
			String[] strList = str02.split(",");
			listUserScore.add(strList);
			// 修改
			avgPaperScore += list.get(x).getSumScore();
			if (x == list.size() - 1) {
				avgPaperScore /= list.size();
			}
		}
		float sumTitleScore = 0;
		float avgTitleScore = 0;
		for (int x = 0; x < list.size(); x++) {
			sumTitleScore += (list.get(x).getSumScore() - avgPaperScore)
					* (list.get(x).getSumScore() - avgPaperScore);
			if (x == list.size() - 1) {
				avgTitleScore = sumTitleScore / (list.size() - 1);
			}
		}

		TitlePaper titlePaper = new TitlePaper();
		titlePaper.setPaperId(paperId);
		Map map01 = Tools.transBean2Map(titlePaper);
		List<TitlePaper> titlePaperList = titlePaperService
				.findByCondition(map01);

		int titleId = 0;
		List titleList = new ArrayList();
		List titleTypeName = new ArrayList();
		List titleTypeList = new ArrayList();
		List list1 = new ArrayList();
		List avgScore = new ArrayList();
		List avgListAll = new ArrayList();
		List<Titletype> titleTypeListAll = new ArrayList();
		int index = 0;
		float sum = 0;
		List listSum = new ArrayList();
		Float[] strtitle = new Float[4];
		List strtitleMax = new ArrayList();
		for (int i = 0; i < titlePaperList.size(); i++) {
			titleId = titlePaperList.get(i).getTitleId();
			titleList.add(titleId);
			Title title = titleService.findById(titleId);
			/**
			 * 把题目的值插入到数组中
			 */
			
			if (title.getAnsweraScore()!= null&& !title.getAnsweraScore().equals("") ) {
				strtitle[0] = title.getAnsweraScore();
			} else {
				strtitle[0] = (float) 0;
			}
			if (title.getAnswerbScore() != null && !title.getAnswerbScore().equals("")) {
				strtitle[1] = title.getAnswerbScore();
			} else {
				strtitle[1] = (float) 0;
			}
			if (title.getAnswercScore() != null && !title.getAnswercScore().equals("")) {
				strtitle[2] = title.getAnswercScore();
			} else {
				strtitle[2] = (float) 0;
			}
			if (title.getAnswerdScore() != null && !title.getAnswerdScore().equals("")) {
				strtitle[3] = title.getAnswerdScore();
			} else {
				strtitle[3] = (float) 0;
			}
	
			strtitleMax.add(getMax(strtitle));
			titleTypeList.add(title.getTitleTypeid());
		}
		// 将题目类型名称无重复的添加list中
		for (int j = 0; j < titleTypeList.size(); j++) {
			if (list1 != null && list1.size() > 0) {
				if (list1.contains(titleTypeList.get(j))) {
					list1.remove(titleTypeList.get(j));
				}
				list1.add(titleTypeList.get(j));

			} else {
				list1.add(titleTypeList.get(j));
			}
		}
		float sum01 = 0;
		// 每种类型正确答案的得分
		List SumList = new ArrayList();
		// 求得每种类型题的总分
		for (int i = 0; i < titleList.size(); i++) {
			if(strListUser[i]==null&&"".equals(strListUser)){
				strListUser[i]=0+"";
			}
			sum = sum + Float.parseFloat(strListUser[i]);
			sum01 = sum01 + Float.parseFloat(strtitleMax.get(i).toString());
			if ((i + 1) % (titleList.size() / list1.size()) == 0) {
				SumList.add(sum01);
				listSum.add(sum);
				float avg = sum / (titleList.size() / list1.size());
				avgScore.add(avg);
				sum = 0;
				sum01 = 0;
			}
		}
		/*
		 * 所有人的总分
		 */
		int index01 = 0;
		float sumList[] = new float[list1.size()];
		List listArray = new ArrayList();
		while (index01 < list.size()) {
			Float[] listArray01 = new Float[titleList.size()];
			for (int i = 0; i < titleList.size(); i++) {
				String[] str01 = new String[titleList.size()];
				str01 = listUserScore.get(index01);
				if(str01[i]==null&&"".equals(str01[i])){
					str01[i]=0+"";
				}
				sum = sum + Float.parseFloat(str01[i]);
				listArray01[i] = Float.parseFloat(str01[i]);
				if ((i + 1) % (titleList.size() / list1.size()) == 0) {
					sumList[i / (titleList.size() / list1.size())] += sum;
					sum = 0;
				}
			}
			listArray.add(listArray01);
			index01++;
		}
		int indexArray = 0;
		List listEveryScore = new ArrayList();
		// 将每个人每道题的成绩都保存在数组中
		while (indexArray < titleList.size()) {
			Float[] listIndex = new Float[listArray.size()];
			for (int i = 0; i < listArray.size(); i++) {
				Float[] listEvery01 = (Float[]) listArray.get(i);
				listIndex[i] = listEvery01[indexArray];
			}
			listEveryScore.add(listIndex);
			indexArray++;
		}

		float sumEveryTitle = 0;
		Float[] avgTitle = new Float[titleList.size()];
		for (int i = 0; i < listEveryScore.size(); i++) {
			Float[] titleEvery = (Float[]) listEveryScore.get(i);
			for (int j = 0; j < titleEvery.length; j++) {
				sumEveryTitle += titleEvery[j];
			}
			avgTitle[i] = sumEveryTitle / titleEvery.length;
			sumEveryTitle = 0;
		}

		float varianceEvery = 0;
		float variance = 0;
		for (int i = 0; i < listEveryScore.size(); i++) {
			Float[] titleEvery01 = (Float[]) listEveryScore.get(i);
			for (int j = 0; j < titleEvery01.length; j++) {
				varianceEvery += (titleEvery01[j] - avgTitle[i])
						* (titleEvery01[j] - avgTitle[i]);
				if (j == titleEvery01.length - 1) {
					varianceEvery = varianceEvery / (list.size() - 1);
					variance += varianceEvery;
					varianceEvery = 0;
					System.out.println(variance);
				}
			}
		}

		/*
		 * 所有人的平均分
		 */
		for (int y = 0; y < sumList.length; y++) {
			int count = titleList.size() / list1.size();
			float avgall = sumList[y] / (count * list.size());
			avgListAll.add(avgall);
		}

		for (int z = 0; z < list1.size(); z++) {
			Titletype titleType = titletypeService.findById(Integer
					.parseInt(list1.get(z).toString()));
			titleTypeListAll.add(titleType);
		}

		// 找到用户的信息
		User u = userService.findById(userPaperList.get(0).getUserId());
		System.out.println(u.toString());
		JSONObject json = new JSONObject();
		if (role.getRoleName().equals("公司用户")) {
			userPaperList.get(0).setState(1);
			userPaperService.update(userPaperList.get(0));

		}
		
		// 求信度
		float w = 0;
		w = Math.abs((titleList.size() * (1 - (variance / avgTitleScore)))
				/ (titleList.size() - 1));
		// 求效度
		float efficiency = 0;
		efficiency = avgPaperScore;
		System.out.println("efficiency" + efficiency);
		paper.setExtend1(w + "");
		paper.setExtend2(efficiency + "");
		paperService.update(paper);
		json.put("titleTypeName", list1);
		json.put("sumScore", listSum);
		json.put("avgScore", avgScore);
		json.put("sumListAll", sumList);
		json.put("avgListAll", avgListAll);
		json.put("paper", paper);
		json.put("userPaperList", userPaperList);
		json.put("user", u);
		json.put("SumList", SumList);
		json.put("titleTypeListAll", titleTypeListAll);
		return json.toString();

	}

	public Float getMax(Float[] str) {
		Float max = str[0];
		for (int i = 0; i < str.length; i++) {
			System.out.println("str" + str[i]);
			if (str[i] >= max) {
				max = str[i];
			}
		}
		return max;
	}

}